home *** CD-ROM | disk | FTP | other *** search
/ Gigarom 1 / Gigarom Macintosh Archives (Quantum Leap)(CDRM1080320)(1993).iso / FILES / DEV / A-B / 002. TESample.cpt / TESample.c < prev    next >
Text File  |  1988-08-01  |  44KB  |  1,394 lines

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source
  10. #
  11. #    Copyright © 1988 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    1.0                    8/88
  15. #
  16. #    Components:    TESample.p            August 1, 1988
  17. #                TESample.c            August 1, 1988
  18. #                TESample.a            August 1, 1988
  19. #                TESample.r            August 1, 1988
  20. #                TESample.h            August 1, 1988
  21. #                PTESample.make        August 1, 1988
  22. #                CTESample.make        August 1, 1988
  23. #
  24. #    TESample is an example application that demonstrates how 
  25. #    to initialize the commonly used toolbox managers, operate 
  26. #    successfully under MultiFinder, handle desk accessories and 
  27. #    create, grow, and zoom windows. The fundamental TextEdit 
  28. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  29. #    also shows how to create and maintain scrollbar controls.
  30. #
  31. #    It does not by any means demonstrate all the techniques you 
  32. #    need for a large application. In particular, Sample does not 
  33. #    cover exception handling, multiple windows/documents, 
  34. #    sophisticated memory management, printing, or undo. All of 
  35. #    these are vital parts of a normal full-sized application.
  36. #
  37. #    This application is an example of the form of a Macintosh 
  38. #    application; it is NOT a template. It is NOT intended to be 
  39. #    used as a foundation for the next world-class, best-selling, 
  40. #    600K application. A stick figure drawing of the human body may 
  41. #    be a good example of the form for a painting, but that does not 
  42. #    mean it should be used as the basis for the next Mona Lisa.
  43. #
  44. #    We recommend that you review this program or Sample before 
  45. #    beginning a new application. Sample is a simple app. which doesn’t 
  46. #    use TextEdit or the Control Manager.
  47. #
  48. ------------------------------------------------------------------------------*/
  49.  
  50.  
  51. /* Segmentation strategy:
  52.  
  53.    This program consists of three segments. Main contains most of the code,
  54.    including the MPW libraries, and the main program. Initialize contains
  55.    code that is only used once, during startup, and can be unloaded after the
  56.    program starts. %A5Init is automatically created by the Linker to initialize
  57.    globals for the MPW libraries and is unloaded right away. */
  58.  
  59.  
  60. /* SetPort strategy:
  61.  
  62.    Toolbox routines do not change the current port. In spite of this, in this
  63.    program we use a strategy of calling SetPort whenever we want to draw or
  64.    make calls which depend on the current port. This makes us less vulnerable
  65.    to bugs in other software which might alter the current port (such as the
  66.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  67.    Hopefully, this also makes the routines from this program more self-contained,
  68.    since they don't depend on the current port setting. */
  69.  
  70.  
  71. /* Clipboard strategy:
  72.  
  73.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  74.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  75.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  76.    the import/export would be in the activate/deactivate event and suspend/resume
  77.    event routines. */
  78.  
  79.  
  80. #include <Values.h>
  81. #include <Types.h>
  82. #include <QuickDraw.h>
  83. #include <Fonts.h>
  84. #include <Events.h>
  85. #include <Controls.h>
  86. #include <Windows.h>
  87. #include <Menus.h>
  88. #include <TextEdit.h>
  89. #include <Dialogs.h>
  90. #include <Desk.h>
  91. #include <Scrap.h>
  92. #include <ToolUtils.h>
  93. #include <Memory.h>
  94. #include <SegLoad.h>
  95. #include <Files.h>
  96. #include <OSUtils.h>
  97. #include <Traps.h>        /* MPW 2.0.2 Traps.h is missing an #endif */
  98. #include <TESample.h>     /* bring in all the #defines for Sample */
  99.  
  100.  
  101. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  102.    as well as the TEHandle for the text we are editing. Other document fields
  103.    can be added to this record as needed. For a similar example, see how the
  104.    Window Manager and Dialog Manager add fields after the GrafPort. */
  105. typedef struct {
  106.     WindowRecord    docWindow;
  107.     TEHandle        docTE;
  108.     ControlHandle    docVScroll;
  109.     ControlHandle    docHScroll;
  110.     ProcPtr            docClik;
  111. } DocumentRecord, *DocumentPeek;
  112.  
  113.  
  114.  
  115. /* The "g" prefix is used to emphasize that a variable is global. */
  116.  
  117. /* GMac is used to hold the result of a SysEnvirons call. This makes
  118.    it convenient for any routine to check the environment. */
  119. SysEnvRec    gMac;                /* set up by Initialize */
  120.  
  121. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  122.    trap is available. If it is false, we know that we must call GetNextEvent. */
  123. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  124.  
  125. /* GInBackground is maintained by our osEvent handling routines. Any part of
  126.    the program can check it to find out if it is currently in the background. */
  127. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  128.  
  129. /* GNumDocuments is used to keep track of how many open documents there are
  130.    at any time. It is maintained by the routines that open and close documents. */
  131. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  132.  
  133.  
  134. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  135.    actual prototypes for parameter type checking. */
  136. #ifndef MPW3
  137.     void EventLoop();
  138.     void DoEvent( /* EventRecord *event */ );
  139.     void AdjustCursor( /* Point mouse, RgnHandle region */ );
  140.     void DoGrowWindow( /* WindowPtr window, EventRecord *event */ );
  141.     void DoZoomWindow( /* WindowPtr window, short part */ );
  142.     void ResizeWindow( /* WindowPtr window */ );
  143.     void GetLocalUpdateRgn( /* WindowPtr window, RgnHandle localRgn */ );
  144.     void DoUpdate( /* WindowPtr window */ );
  145.     void DoDeactivate( /* WindowPtr window */ );
  146.     void DoActivate( /* WindowPtr window, Boolean becomingActive */ );
  147.     void DoContentClick( /* WindowPtr window, EventRecord *event */ );
  148.     void DoKeyDown( /* EventRecord *event */ );
  149.     unsigned long GetSleep();
  150.     void CommonAction( /* ControlHandle control, short *amount */ );
  151.     pascal void VActionProc( /* ControlHandle control, short part */ );
  152.     pascal void HActionProc( /* ControlHandle control, short part */ );
  153.     void DoIdle();
  154.     void DrawWindow( /* WindowPtr window */ );
  155.     void AdjustMenus();
  156.     void DoMenuCommand( /* long menuResult */ );
  157.     void DoNew();
  158.     void DoCloseWindow( /* WindowPtr window */ );
  159.     void DoCloseBehind( /* WindowPtr window */ );
  160.     void Terminate();
  161.     void Initialize();
  162.     void ForceEnvirons();
  163.     void GetTERect( /* WindowPtr window, Rect *teRect */ );
  164.     void AdjustViewRect( /* TEHandle docTE */ );
  165.     void AdjustTE( /* WindowPtr window */ );
  166.     void AdjustHV( /* Boolean isVert, ControlHandle control, TEHandle docTE,
  167.                     Boolean canRedraw */ );
  168.     void AdjustScrollValues( /* WindowPtr window, Boolean canRedraw */ );
  169.     void AdjustScrollSizes( /* WindowPtr window */ );
  170.     void AdjustScrollbars( /* WindowPtr window, Boolean needsResize */ );
  171.     pascal void PascalClikLoop();
  172.     pascal ProcPtr GetOldClikLoop();
  173.     Boolean IsAppWindow( /* WindowPtr window */ );
  174.     Boolean IsDAWindow( /* WindowPtr window */ );
  175.     Boolean TrapAvailable( /* short tNumber, TrapType tType */ );
  176. #else
  177.     void EventLoop( void );
  178.     void DoEvent( EventRecord *event );
  179.     void AdjustCursor( Point mouse, RgnHandle region );
  180.     void DoGrowWindow( WindowPtr window, EventRecord *event );
  181.     void DoZoomWindow( WindowPtr window, short part );
  182.     void ResizeWindow( WindowPtr window );
  183.     void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  184.     void DoUpdate( WindowPtr window );
  185.     void DoDeactivate( WindowPtr window );
  186.     void DoActivate( WindowPtr window, Boolean becomingActive );
  187.     void DoContentClick( WindowPtr window, EventRecord *event );
  188.     void DoKeyDown( EventRecord *event );
  189.     unsigned long GetSleep( void );
  190.     void CommonAction( ControlHandle control, short *amount );
  191.     pascal void VActionProc( ControlHandle control, short part );
  192.     pascal void HActionProc( ControlHandle control, short part );
  193.     void DoIdle( void );
  194.     void DrawWindow( WindowPtr window );
  195.     void AdjustMenus( void );
  196.     void DoMenuCommand( long menuResult );
  197.     void DoNew( void );
  198.     void DoCloseWindow( WindowPtr window );
  199.     void DoCloseBehind( WindowPtr window );
  200.     void Terminate( void );
  201.     void Initialize( void );
  202.     void ForceEnvirons( void );
  203.     void GetTERect( WindowPtr window, Rect *teRect );
  204.     void AdjustViewRect( TEHandle docTE );
  205.     void AdjustTE( WindowPtr window );
  206.     void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
  207.                     Boolean canRedraw );
  208.     void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  209.     void AdjustScrollSizes( WindowPtr window );
  210.     void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  211.     pascal void PascalClikLoop();
  212.     pascal ProcPtr GetOldClikLoop();
  213.     Boolean IsAppWindow( WindowPtr window );
  214.     Boolean IsDAWindow( WindowPtr window );
  215.     Boolean TrapAvailable( short tNumber, TrapType tType );
  216. #endif
  217.  
  218.  
  219. /* Make the 2.0 Interface for passing Points to the Toolbox by address,
  220.    emulate the 3.0 method of passing Points by value. This list only contains
  221.    the affected routines actually used in this sample, and is not intended to
  222.    be a comprehensive list of the affected routines.
  223.  
  224.    For routines that have Str255 formal parameters we cannot do a similar trick
  225.    so the necessary changes are in the code itself. Searching for MPW3 will find
  226.    them. */
  227. #ifndef MPW3
  228. #    define FindWindow    FINDWINDOW
  229. #    define MenuSelect    MENUSELECT
  230. #    define DragWindow    DRAGWINDOW
  231. #    define TrackGoAway    TRACKGOAWAY
  232. #    define PtInRgn        PTINRGN
  233. #    define TEClick        TECLICK
  234. #    define FindControl    FINDCONTROL
  235. #    define TrackControl    TRACKCONTROL
  236. #    define GrowWindow    GROWWINDOW
  237. #    define TrackBox        TRACKBOX
  238. pascal void Debugger()
  239.     extern 0xA9FF;
  240. #endif
  241.  
  242. /* Define HiWrd and LoWrd macros for efficiency. */
  243. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  244. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  245.  
  246. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  247.    dependency on the ordering of fields within a Rect */
  248. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  249. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  250.  
  251.  
  252. /* This routine is part of the MPW runtime library. This external
  253.    reference to it is done so that we can unload its segment, %A5Init. */
  254.  
  255. extern void _DataInit();
  256.  
  257.  
  258. /* A reference to our assembly language routine that gets attached to the clikLoop
  259. field of our TE record. */
  260.  
  261. extern pascal void AsmClikLoop();
  262.  
  263.  
  264. #define __SEG__ Main
  265. main()
  266. {
  267.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  268.     ForceEnvirons();                /* check for some basic requirements; exits if not met */
  269.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  270.  
  271.     Initialize();                    /* initialize the program */
  272.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  273.  
  274.     EventLoop();                    /* call the main event loop */
  275. }
  276.  
  277.  
  278. /* Get events forever, and handle them by calling DoEvent.
  279.    Also call AdjustCursor each time through the loop. */
  280.  
  281. #define __SEG__ Main
  282. void EventLoop()
  283. {
  284.     RgnHandle    cursorRgn;
  285.     Boolean        gotEvent;
  286.     EventRecord    event;
  287.  
  288.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  289.     do {
  290.         /* use WNE if it is available */
  291.         if ( gHasWaitNextEvent )
  292.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  293.         else {
  294.             SystemTask();
  295.             gotEvent = GetNextEvent(everyEvent, &event);
  296.         }
  297.         if ( gotEvent ) {
  298.             /* make sure we have the right cursor before handling the event */
  299.             AdjustCursor(event.where, cursorRgn);
  300.             DoEvent(&event);
  301.         }
  302.         else
  303.             DoIdle();                /* perform idle tasks when it’s not our event */
  304.         /* change the cursor (and region) if necessary */
  305.         AdjustCursor(event.where, cursorRgn);
  306.     } while ( true );    /* loop forever; we quit via ExitToShell */
  307. } /*EventLoop*/
  308.  
  309.  
  310. /* Do the right thing for an event. Determine what kind of event it is, and call
  311.  the appropriate routines. */
  312.  
  313. #define __SEG__ Main
  314. void DoEvent(event)
  315.     EventRecord    *event;
  316. {
  317.     short        part;
  318.     WindowPtr    window;
  319.     char        key;
  320.  
  321.     switch ( event->what ) {
  322.         case nullEvent:
  323.             /* we idle for null/mouse moved events ands for events which aren’t
  324.                 ours (see EventLoop) */
  325.             DoIdle();
  326.             break;
  327.         case mouseDown:
  328.             part = FindWindow(event->where, &window);
  329.             switch ( part ) {
  330.                 case inMenuBar:             /* process a mouse menu command (if any) */
  331.                     AdjustMenus();    /* bring ’em up-to-date */
  332.                     DoMenuCommand(MenuSelect(event->where));
  333.                     break;
  334.                 case inSysWindow:           /* let the system handle the mouseDown */
  335.                     SystemClick(event, window);
  336.                     break;
  337.                 case inContent:
  338.                     if ( window != FrontWindow() ) {
  339.                         SelectWindow(window);
  340.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  341.                     } else
  342.                         DoContentClick(window, event);
  343.                     break;
  344.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  345.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  346.                     break;
  347.                 case inGoAway:
  348.                     if ( TrackGoAway(window, event->where) )
  349.                         DoCloseWindow(window);
  350.                     break;
  351.                 case inGrow:
  352.                     DoGrowWindow(window, event);
  353.                     break;
  354.                 case inZoomIn:
  355.                 case inZoomOut:
  356.                 if ( TrackBox(window, event->where, part) )
  357.                         DoZoomWindow(window, part);
  358.                     break;
  359.             }
  360.             break;
  361.         case keyDown:
  362.         case autoKey:                       /* check for menukey equivalents */
  363.             key = event->message & charCodeMask;
  364.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  365.                 if ( event->what == keyDown ) {
  366.                     AdjustMenus();            /* enable/disable/check menu items properly */
  367.                     DoMenuCommand(MenuKey(key));
  368.                 }
  369.             } else
  370.                 DoKeyDown(event);
  371.             break;
  372.         case activateEvt:
  373.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  374.             break;
  375.         case updateEvt:
  376.             DoUpdate((WindowPtr) event->message);
  377.             break;
  378.         case osEvent:
  379.             switch (event->message >> 24) {     /* high byte of message */
  380.                 case mouseMovedMessage:
  381.                     DoIdle();                    /* mouse-moved is also an idle event */
  382.                     break;
  383.                 case suspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  384.                     gInBackground = (event->message & resumeMask) == 0;
  385.                     DoActivate(FrontWindow(), !gInBackground);
  386.                     break;
  387.             }
  388.             break;
  389.     }
  390. } /*DoEvent*/
  391.  
  392.  
  393. /*    Change the cursor's shape, depending on its position. This also calculates the region
  394.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  395.     this region, an event is generated. If there is more to the event than just
  396.     “the mouse moved”, we get called before the event is processed to make sure
  397.     the cursor is the right one. In any (ahem) event, this is called again before we
  398.     fall back into WNE. */
  399.  
  400. #define __SEG__ Main
  401. void AdjustCursor(mouse,region)
  402.     Point        mouse;
  403.     RgnHandle    region;
  404. {
  405.     WindowPtr    window;
  406.     RgnHandle    arrowRgn;
  407.     RgnHandle    iBeamRgn;
  408.     Rect        iBeamRect;
  409.  
  410.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  411.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  412.         /* calculate regions for different cursor shapes */
  413.         arrowRgn = NewRgn();
  414.         iBeamRgn = NewRgn();
  415.  
  416.         /* start arrowRgn wide open */
  417.         SetRectRgn(arrowRgn, extremeNeg, extremeNeg, extremePos, extremePos);
  418.  
  419.         /* calculate iBeamRgn */
  420.         if ( IsAppWindow(window) ) {
  421.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  422.             SetPort(window);    /* make a global version of the viewRect */
  423.             LocalToGlobal(&TopLeft(iBeamRect));
  424.             LocalToGlobal(&BotRight(iBeamRect));
  425.             RectRgn(iBeamRgn, &iBeamRect);
  426.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  427.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  428.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  429.             SetOrigin(0, 0);
  430.         }
  431.  
  432.         /* subtract other regions from arrowRgn */
  433.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  434.  
  435.         /* change the cursor and the region parameter */
  436.         if ( PtInRgn(mouse, iBeamRgn) ) {
  437.             SetCursor(*GetCursor(iBeamCursor));
  438.             CopyRgn(iBeamRgn, region);
  439.         } else {
  440.             SetCursor(&qd.arrow);
  441.             CopyRgn(arrowRgn, region);
  442.         }
  443.  
  444.         DisposeRgn(arrowRgn);
  445.         DisposeRgn(iBeamRgn);
  446.     }
  447. } /*AdjustCursor*/
  448.  
  449.  
  450. /*    Called when a mouseDown occurs in the grow box of an active window. In
  451.     order to eliminate any 'flicker', we want to invalidate only what is
  452.     necessary. Since ResizeWindow invalidates the whole portRect, we save
  453.     the old TE viewRect, intersect it with the new TE viewRect, and
  454.     remove the result from the update region. However, we must make sure
  455.     that any old update region that might have been around gets put back. */
  456.  
  457. #define __SEG__ Main
  458. void DoGrowWindow(window,event)
  459.     WindowPtr    window;
  460.     EventRecord    *event;
  461. {
  462.     long        growResult;
  463.     Rect        tempRect;
  464.     RgnHandle    tempRgn;
  465.     Boolean        ignoreResult;
  466.     DocumentPeek doc;
  467.     
  468.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  469.     tempRect.left = minDocDim;
  470.     tempRect.top = minDocDim;
  471.     growResult = GrowWindow(window, event->where, &tempRect);
  472.     /* see if it really changed size */
  473.     if ( growResult != 0 ) {
  474.         doc = (DocumentPeek) window;
  475.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  476.         tempRgn = NewRgn();
  477.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  478.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  479.         ResizeWindow(window);
  480.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  481.         ignoreResult = SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  482.         ValidRect(&tempRect);                            /* take it out of update */
  483.         InvalRgn(tempRgn);                                /* put back any prior update */
  484.         DisposeRgn(tempRgn);
  485.     }
  486. } /* DoGrowWindow */
  487.  
  488.  
  489. /*     Called when a mouseClick occurs in the zoom box of an active window.
  490.     Everything has to get re-drawn here, so we don't mind that
  491.     ResizeWindow invalidates the whole portRect. */
  492.  
  493. #define __SEG__ Main
  494. void DoZoomWindow(window,part)
  495.     WindowPtr    window;
  496.     short        part;
  497. {
  498.     EraseRect(&window->portRect);
  499.     ZoomWindow(window, part, window == FrontWindow());
  500.     ResizeWindow(window);
  501. } /*  DoZoomWindow */
  502.  
  503.  
  504. /* Called when the window has been resized to fix up the controls and content. */
  505. #define __SEG__ Main
  506. void ResizeWindow(window)
  507.     WindowPtr    window;
  508. {
  509.     AdjustScrollbars(window, true);
  510.     AdjustTE(window);
  511.     InvalRect(&window->portRect);
  512. } /* ResizeWindow */
  513.  
  514.  
  515. /* Returns the update region in local coordinates */
  516. #define __SEG__ Main
  517. void GetLocalUpdateRgn(window,localRgn)
  518.     WindowPtr    window;
  519.     RgnHandle    localRgn;
  520. {
  521.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  522.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  523. } /* GetLocalUpdateRgn */
  524.  
  525.  
  526. /*    This is called when an update event is received for a window.
  527.     It calls DrawWindow to draw the contents of an application window.
  528.     As an efficiency measure that does not have to be followed, it
  529.     calls the drawing routine only if the visRgn is non-empty. This
  530.     will handle situations where calculations for drawing or drawing
  531.     itself is very time-consuming. */
  532.  
  533. #define __SEG__ Main
  534. void DoUpdate(window)
  535.     WindowPtr    window;
  536. {
  537.     if ( IsAppWindow(window) ) {
  538.         BeginUpdate(window);                /* this sets up the visRgn */
  539.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  540.             DrawWindow(window);
  541.         EndUpdate(window);
  542.     }
  543. } /*DoUpdate*/
  544.  
  545.  
  546. /*    This is called when a window is activated or deactivated.
  547.     It calls TextEdit to deal with the selection. */
  548.  
  549. #define __SEG__ Main
  550. void DoActivate(window, becomingActive)
  551.     WindowPtr    window;
  552.     Boolean        becomingActive;
  553. {
  554.     RgnHandle    tempRgn;
  555.     RgnHandle    clipRgn;
  556.     DocumentPeek doc;
  557.     
  558.     if ( IsAppWindow(window) ) {
  559.         doc = (DocumentPeek) window;
  560.         if ( becomingActive ) {
  561.             /*    since we don’t want TEActivate to draw a selection in an area where
  562.                 we’re going to erase and redraw, we’ll clip out the update region
  563.                 before calling it. */
  564.             tempRgn = NewRgn();
  565.             clipRgn = NewRgn();
  566.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  567.             GetClip(clipRgn);
  568.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  569.             SetClip(tempRgn);
  570.             TEActivate(doc->docTE);
  571.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  572.             DisposeRgn(tempRgn);
  573.             DisposeRgn(clipRgn);
  574.             
  575.             /* the controls must be redrawn on activation: */
  576.             (*doc->docVScroll)->contrlVis = controlVisible;
  577.             (*doc->docHScroll)->contrlVis = controlVisible;
  578.             InvalRect(&(*doc->docVScroll)->contrlRect);
  579.             InvalRect(&(*doc->docHScroll)->contrlRect);
  580.         }
  581.         else {        
  582.             TEDeactivate(doc->docTE);
  583.             /* the controls must be hidden on deactivation: */
  584.             HideControl(doc->docVScroll);
  585.             HideControl(doc->docHScroll);
  586.         }
  587.     }
  588. } /*DoActivate*/
  589.  
  590.  
  591. /*    This is called when a mouseDown occurs in the content of a window. */
  592.  
  593. #define __SEG__ Main
  594. void DoContentClick(window,event)
  595.     WindowPtr    window;
  596.     EventRecord    *event;
  597. {
  598.     Point        mouse;
  599.     ControlHandle control;
  600.     short        part, value;
  601.     Boolean        shiftDown;
  602.     DocumentPeek doc;
  603.  
  604.     if ( IsAppWindow(window) ) {
  605.         SetPort(window);
  606.         mouse = event->where;                            /* get the click position */
  607.         GlobalToLocal(&mouse);
  608.         part = FindControl(mouse, window, &control);
  609.         doc = (DocumentPeek) window;
  610.         switch ( part ) {
  611.             case 0:                            /* not in a control*/
  612.                 /* see if we need to extend the selection */
  613.                 shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  614.                 TEClick(mouse, shiftDown, doc->docTE);
  615.                 break;
  616.             case inThumb:
  617.                 value = GetCtlValue(control);
  618.                 part = TrackControl(control, mouse, nil);
  619.                 if ( part != 0 ) {
  620.                     value -= GetCtlValue(control);
  621.                     /* value now has CHANGE in value; if value changed, scroll */
  622.                     if ( value != 0 )
  623.                         if ( control == doc->docVScroll )
  624.                             TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  625.                         else
  626.                             TEScroll(value, 0, doc->docTE);
  627.                 }
  628.                 break;
  629.             default:                        /* they clicked in an arrow, so track & scroll */
  630.                 if ( control == doc->docVScroll )
  631.                     value = TrackControl(control, mouse, (ProcPtr) VActionProc);
  632.                 else
  633.                     value = TrackControl(control, mouse, (ProcPtr) HActionProc);
  634.                 break;
  635.         }
  636.     }
  637. } /*DoContentClick*/
  638.  
  639.  
  640. /* This is called for any keyDown or autoKey events, except when the
  641.  Command key is held down. It looks at the frontmost window to decide what
  642.  to do with the key typed. */
  643.  
  644. #define __SEG__ Main
  645. void DoKeyDown(event)
  646.     EventRecord    *event;
  647. {
  648.     WindowPtr    window;
  649.     char        key;
  650.     TEHandle    te;
  651.  
  652.     window = FrontWindow();
  653.     if ( IsAppWindow(window) ) {
  654.         te = ((DocumentPeek) window)->docTE;
  655.         key = event->message & charCodeMask;
  656.         /* we have a char. for our window; see if we are still below TextEdit’s
  657.             limit for the number of characters */
  658.         if ( (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  659.                 maxTELength ) {
  660.             TEKey(key, te);
  661.             AdjustScrollbars(window, false);
  662.             AdjustTE(window);
  663.         } else
  664.             SysBeep(8);
  665.     }
  666. } /*DoKeyDown*/
  667.  
  668.  
  669. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  670.     that DoIdle does with idle time. */
  671.  
  672. #define __SEG__ Main
  673. unsigned long GetSleep()
  674. {
  675.     long        sleep;
  676.     WindowPtr    window;
  677.     TEHandle    te;
  678.  
  679.     sleep = MAXLONG;                        /* default value for sleep */
  680.     if ( !gInBackground ) {
  681.         window = FrontWindow();            /* and the front window is ours... */
  682.         if ( IsAppWindow(window) ) {
  683.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  684.             if ( (*te)->selStart == (*te)->selEnd )
  685.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  686.         }
  687.     }
  688.     return sleep;
  689. } /*GetSleep*/
  690.  
  691.  
  692. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  693.     the value of the control changed. Note the pinning is done for the sake of returning
  694.     the amount the control value changed. */
  695.  
  696. #define __SEG__ Main
  697. void CommonAction(control,amount)
  698.     ControlHandle control;
  699.     short        *amount;
  700. {
  701.     short        value, max;
  702.     
  703.     value = GetCtlValue(control);    /* get current value */
  704.     max = GetCtlMax(control);        /* and maximum value */
  705.     *amount = value - *amount;
  706.     if ( *amount < 0 )
  707.         *amount = 0;
  708.     else if ( *amount > max )
  709.         *amount = max;
  710.     SetCtlValue(control, *amount);
  711.     *amount = value - *amount;        /* calculate the real change */
  712. } /* CommonAction */
  713.  
  714.  
  715. /* Determines how much to change the value of the vertical scrollbar by and how
  716.     much to scroll the TE record. */
  717.  
  718. #define __SEG__ Main
  719. pascal void VActionProc(control,part)
  720.     ControlHandle control;
  721.     short        part;
  722. {
  723.     short        amount;
  724.     WindowPtr    window;
  725.     TEPtr        te;
  726.     
  727.     if ( part != 0 ) {                /* if it was actually in the control */
  728.         window = (*control)->contrlOwner;
  729.         te = *((DocumentPeek) window)->docTE;
  730.         switch ( part ) {
  731.             case inUpButton:
  732.             case inDownButton:        /* one line */
  733.                 amount = 1;
  734.                 break;
  735.             case inPageUp:            /* one page */
  736.             case inPageDown:
  737.                 amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  738.                 break;
  739.         }
  740.         if ( (part == inDownButton) || (part == inPageDown) )
  741.             amount = -amount;        /* reverse direction for a downer */
  742.         CommonAction(control, &amount);
  743.         if ( amount != 0 )
  744.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  745.     }
  746. } /* VActionProc */
  747.  
  748.  
  749. /* Determines how much to change the value of the horizontal scrollbar by and how
  750. much to scroll the TE record. */
  751.  
  752. #define __SEG__ Main
  753. pascal void HActionProc(control,part)
  754.     ControlHandle control;
  755.     short        part;
  756. {
  757.     short        amount;
  758.     WindowPtr    window;
  759.     TEPtr        te;
  760.     
  761.     if ( part != 0 ) {
  762.         window = (*control)->contrlOwner;
  763.         te = *((DocumentPeek) window)->docTE;
  764.         switch ( part ) {
  765.             case inUpButton:
  766.             case inDownButton:        /* a few pixels */
  767.                 amount = buttonScroll;
  768.                 break;
  769.             case inPageUp:            /* a page */
  770.             case inPageDown:
  771.                 amount = te->viewRect.right - te->viewRect.left;
  772.                 break;
  773.         }
  774.         if ( (part == inDownButton) || (part == inPageDown) )
  775.             amount = -amount;        /* reverse direction */
  776.         CommonAction(control, &amount);
  777.         if ( amount != 0 )
  778.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  779.     }
  780. } /* VActionProc */
  781.  
  782.  
  783. /* This is called whenever we get a null event et al.
  784.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  785.  
  786. #define __SEG__ Main
  787. void DoIdle()
  788. {
  789.     WindowPtr    window;
  790.  
  791.     window = FrontWindow();
  792.     if ( IsAppWindow(window) )
  793.         TEIdle(((DocumentPeek) window)->docTE);
  794. } /*DoIdle*/
  795.  
  796.  
  797. /* Draw the contents of an application window. */
  798.  
  799. #define __SEG__ Main
  800. void DrawWindow(window)
  801.     WindowPtr    window;
  802. {
  803.     SetPort(window);
  804.     EraseRect(&window->portRect);
  805.     DrawControls(window);
  806.     DrawGrowIcon(window);
  807.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  808. } /*DrawWindow*/
  809.  
  810.  
  811. /*    Enable and disable menus based on the current state.
  812.     The user can only select enabled menu items. We set up all the menu items
  813.     before calling MenuSelect or MenuKey, since these are the only times that
  814.     a menu item can be selected. Note that MenuSelect is also the only time
  815.     the user will see menu items. This approach to deciding what enable/
  816.     disable state a menu item has the advantage of concentrating all
  817.     the decision-making in one routine, as opposed to being spread throughout
  818.     the application. Other application designs may take a different approach
  819.     that is just as valid. */
  820.  
  821. #define __SEG__ Main
  822. void AdjustMenus()
  823. {
  824.     WindowPtr    window;
  825.     MenuHandle    menu;
  826.     long        offset;
  827.     Boolean        undo;
  828.     Boolean        cutCopyClear;
  829.     Boolean        paste;
  830.     TEHandle    te;
  831.  
  832.     window = FrontWindow();
  833.  
  834.     menu = GetMHandle(mFile);
  835.     if ( gNumDocuments < maxOpenDocuments )
  836.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  837.     else
  838.         DisableItem(menu, iNew);
  839.     if ( window != nil )            /* Close is enabled when there is a window to close */
  840.         EnableItem(menu, iClose);
  841.     else
  842.         DisableItem(menu, iClose);
  843.  
  844.     menu = GetMHandle(mEdit);
  845.     undo = false;
  846.     cutCopyClear = false;
  847.     paste = false;
  848.     if ( IsDAWindow(window) ) {
  849.         undo = true;                /* all editing is enabled for DA windows */
  850.         cutCopyClear = true;
  851.         paste = true;
  852.     } else if ( IsAppWindow(window) ) {
  853.         te = ((DocumentPeek) window)->docTE;
  854.         if ( (*te)->selStart < (*te)->selEnd )
  855.             cutCopyClear = true;
  856.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  857.         if ( GetScrap(nil, 'TEXT', &offset) )
  858.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  859.     }
  860.     if ( undo )
  861.         EnableItem(menu, iUndo);
  862.     else
  863.         DisableItem(menu, iUndo);
  864.     if ( cutCopyClear ) {
  865.         EnableItem(menu, iCut);
  866.         EnableItem(menu, iCopy);
  867.         EnableItem(menu, iClear);
  868.     } else {
  869.         DisableItem(menu, iCut);
  870.         DisableItem(menu, iCopy);
  871.         DisableItem(menu, iClear);
  872.     }
  873.     if ( paste )
  874.         EnableItem(menu, iPaste);
  875.     else
  876.         DisableItem(menu, iPaste);
  877. } /*AdjustMenus*/
  878.  
  879.  
  880. /*    This is called when an item is chosen from the menu bar (after calling
  881.     MenuSelect or MenuKey). I It performs the right operation for each command.
  882.     It is good to have both the result of MenuSelect and MenuKey go to
  883.     one routine like this to keep everything organized. */
  884.  
  885. #define __SEG__ Main
  886. void DoMenuCommand(menuResult)
  887.     long        menuResult;
  888. {
  889.     short        menuID;             /* the resource ID of the selected menu */
  890.     short        menuItem;           /* the item number of the selected menu */
  891.     short        itemHit;
  892.     Str255        daName;
  893.     short        daRefNum;
  894.     OSErr        ignoreResult;
  895.     TEHandle    te;
  896.     WindowPtr    window;
  897.  
  898.     window = FrontWindow();
  899.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  900.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  901.     switch ( menuID ) {
  902.         case mApple:
  903.             switch ( menuItem ) {
  904.                 case iAbout:        /* bring up alert for About */
  905.                     itemHit = Alert(rAboutAlert, nil);
  906.                     break;
  907.                 default:            /* all non-About items in this menu are DAs et al */
  908. #                    ifndef MPW3
  909.                         /* type Str255 is a struct in MPW 2 */
  910.                         GETITEM(GetMHandle(mApple), menuItem, &daName);
  911.                         daRefNum = OPENDESKACC(&daName);
  912. #                    else
  913.                         /* type Str255 is an array in MPW 3 */
  914.                         GetItem(GetMHandle(mApple), menuItem, daName);
  915.                         daRefNum = OpenDeskAcc(daName);
  916. #                    endif
  917.                     break;
  918.             }
  919.             break;
  920.         case mFile:
  921.             switch ( menuItem ) {
  922.                 case iNew:
  923.                     DoNew();
  924.                     break;
  925.                 case iClose:
  926.                     DoCloseWindow(FrontWindow());
  927.                     break;
  928.                 case iQuit:
  929.                     Terminate();
  930.                     break;
  931.             }
  932.             break;
  933.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  934.             if ( !SystemEdit(menuItem-1) ) {
  935.                 te = ((DocumentPeek) FrontWindow())->docTE;
  936.                 switch ( menuItem ) {
  937.                     case iCut:
  938.                         if ( ZeroScrap() == noErr ) {
  939.                             TECut(te);    /* after cutting, export the TE scrap */
  940.                             if ( TEToScrap() != noErr ) {
  941.                                 SetCursor(&qd.arrow);
  942.                                 /* alert user if we couldn’t cut */
  943.                                 itemHit = Alert(rEditAlert, nil);
  944.                                 ignoreResult = ZeroScrap();
  945.                             }
  946.                         }
  947.                         break;
  948.                     case iCopy:
  949.                         if ( ZeroScrap() == noErr ) {
  950.                             TECopy(te);    /* after copying, export the TE scrap */
  951.                             if ( TEToScrap() != noErr ) {
  952.                                 SetCursor(&qd.arrow);
  953.                                 /* alert user if we couldn’t copy */
  954.                                 itemHit = Alert(rEditAlert, nil);
  955.                                 ignoreResult = ZeroScrap();
  956.                             }
  957.                         }
  958.                         break;
  959.                     case iPaste:    /* import the TE scrap before pasting */
  960.                         if ( TEFromScrap() == noErr )
  961.                             if ( TEGetScrapLen() + ((*te)->teLength -
  962.                                 ((*te)->selEnd - (*te)->selStart)) < maxTELength )
  963.                                 TEPaste(te);
  964.                             else {
  965.                                 SetCursor(&qd.arrow);
  966.                                 /* alert user if this would exceed the limit for chars */
  967.                                 itemHit = Alert(rEditAlert, nil);
  968.                             }
  969.                         break;
  970.                     case iClear:
  971.                         TEDelete(te);
  972.                         break;
  973.                 }
  974.             AdjustScrollbars(window, false);
  975.             AdjustTE(window);
  976.             }
  977.             break;
  978.     }
  979.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  980. } /*DoMenuCommand*/
  981.  
  982.  
  983. /* Create a new document and window. */
  984.  
  985. #define __SEG__ Main
  986. void DoNew()
  987. {
  988.     Boolean        good;
  989.     Ptr            storage;
  990.     WindowPtr    window;
  991.     Rect        destRect, viewRect;
  992.     DocumentPeek doc;
  993.  
  994.     storage = NewPtr(sizeof(DocumentRecord));
  995.     if ( storage != nil ) {
  996.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  997.         if ( window != nil ) {
  998.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  999.             good = false;
  1000.             SetPort(window);
  1001.             doc =  (DocumentPeek) window;
  1002.             GetTERect(window, &viewRect);
  1003.             destRect = viewRect;
  1004.             destRect.right = destRect.left + maxDocWidth;
  1005.             doc->docTE = TENew(&destRect, &viewRect);
  1006.             AdjustViewRect(doc->docTE);
  1007.             TEAutoView(true, doc->docTE);
  1008.             doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
  1009. #ifndef MPW3
  1010.             (*doc->docTE)->clikLoop = (ProcPtr) AsmClikLoop;
  1011. #else
  1012.             (*doc->docTE)->clikLoop = (ClikLoopProcPtr) AsmClikLoop;
  1013. #endif
  1014.             
  1015.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  1016.             if ( good ) {                /* good document? — get scrollbars */
  1017.                 doc->docVScroll = GetNewControl(rVScroll, window);
  1018.                 good = (doc->docVScroll != nil);
  1019.             }
  1020.             if ( good) {
  1021.                 doc->docHScroll = GetNewControl(rHScroll, window);
  1022.                 good = (doc->docHScroll != nil);
  1023.             }
  1024.             
  1025.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  1026.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  1027.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  1028.                 AdjustScrollValues(window, false);
  1029.                 ShowWindow(window);
  1030.             } else {
  1031.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1032.                 SysBeep(8);                /* and beep (8 is an arbitrary duration) */
  1033.             }
  1034.         } else
  1035.             DisposPtr(storage);            /* get rid of the storage if it is never used */
  1036.     }
  1037. } /*DoNew*/
  1038.  
  1039.  
  1040. /* Close a window. This handles desk accessory and application windows. */
  1041.  
  1042. #define __SEG__ Main
  1043. void DoCloseWindow(window)
  1044.     WindowPtr    window;
  1045. {
  1046.     TEHandle    te;
  1047.  
  1048.     if ( IsDAWindow(window) )
  1049.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1050.     else if ( IsAppWindow(window) ) {
  1051.         te = ((DocumentPeek) window)->docTE;
  1052.         if ( te != nil )
  1053.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1054.         DisposeWindow(window);
  1055.         gNumDocuments -= 1;
  1056.     }
  1057. } /*DoCloseWindow*/
  1058.  
  1059.  
  1060. /*    Close the window that is passed and all windows behind it.
  1061.     This closes windows from back to front, by calling itself
  1062.     recursively, which minimizes window updating. Always keep
  1063.     in mind the dangers of stack overflow when recursive routines
  1064.     are used in situations where the calling level gets too
  1065.     deep. That is not a problem here. */
  1066.  
  1067. #define __SEG__ Main
  1068. void DoCloseBehind(window)
  1069.     WindowPtr    window;
  1070. {
  1071.     if ( window != nil ) {    /* if we are passed a window, close other windows behind it first */
  1072.         DoCloseBehind((WindowPtr) (((WindowPeek) window)->nextWindow));
  1073.         DoCloseWindow(window);    /* now that all the windows behind are closed, close this one */
  1074.     }
  1075. } /*DoCloseBehind*/
  1076.  
  1077.  
  1078. /* Clean up the application and exits. We close all of the windows so that
  1079.  they can update their documents, if any. */
  1080.  
  1081. #define __SEG__ Main
  1082. void Terminate()
  1083. {
  1084.     DoCloseBehind(FrontWindow());    /* close all windows */
  1085.     ExitToShell();
  1086. } /*Terminate*/
  1087.  
  1088.  
  1089. /*    Set up the whole world, including global variables, Toolbox managers,
  1090.     menus, and a single blank document. */
  1091.  
  1092. #define __SEG__ Initialize
  1093. void Initialize()
  1094. {
  1095.     Handle    menuBar;
  1096.  
  1097.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1098.     gInBackground = false;
  1099.  
  1100.     InitGraf((Ptr) &qd.thePort);
  1101.     InitFonts();
  1102.     InitWindows();
  1103.     InitMenus();
  1104.     TEInit();
  1105.     InitDialogs(nil);
  1106.     InitCursor();
  1107.  
  1108.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1109.     if ( menuBar == nil ) ExitToShell();
  1110.     SetMenuBar(menuBar);                    /* install menus */
  1111.     DisposHandle(menuBar);
  1112.     AddResMenu(GetMHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1113.     DrawMenuBar();
  1114.  
  1115.     gNumDocuments = 0;
  1116.  
  1117.     /* do other initialization here */
  1118.  
  1119.     DoNew();                                /* create a single empty document */
  1120. } /*Initialize*/
  1121.  
  1122.  
  1123. /*    Make sure that the machine has at least 128K ROMs and enough memory to run.
  1124.     If it doesn't, exit. SysEnvirons can be called before the toolbox managers
  1125.     are initialized, and we need to call it at this point so we can check for
  1126.     the right ROMs and memory availability before we call MaxApplZone and
  1127.     initialize the toolbox managers. If AppleTalk has not been initialized, you
  1128.     won't get the version of the AppleTalk driver that is running. That is not
  1129.     critical here, and if that information was required, SysEnvirons could be
  1130.     called again after AppleTalk had been initialized. */
  1131.  
  1132. #define __SEG__ Main
  1133. void ForceEnvirons()
  1134. {
  1135.     OSErr    ignoreError;
  1136.  
  1137.     /* ignore the error returned from SysEnvirons; even if an error occurred,
  1138.        the SysEnvirons glue will fill in the SysEnvRec */
  1139.     ignoreError = SysEnvirons(sysEnvironsVersion, &gMac);
  1140.     if ( (gMac.machineType < 0) ||
  1141.         (StackSpace() + (long) GetApplLimit() - (long) ApplicZone() < kMinSize * 1024) )
  1142.         ExitToShell();
  1143.     /* if you have stack requirements that differ from the default,
  1144.        then you could use SetApplLimit to increase StackSpace at this point. */
  1145. } /* ForceEnvirons */
  1146.  
  1147.  
  1148. /* Return a rectangle that is inset from the portRect by the size of
  1149.     the scrollbars and a little extra margin. */
  1150.  
  1151. #define __SEG__ Main
  1152. void GetTERect(window,teRect)
  1153.     WindowPtr    window;
  1154.     Rect        *teRect;
  1155. {
  1156.     *teRect = window->portRect;
  1157.     InsetRect(teRect, textMargin, textMargin);    /* adjust for margin */
  1158.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1159.     teRect->right = teRect->right - 15;
  1160. } /*GetTERect*/
  1161.  
  1162.  
  1163. /* Update the TERec's view rect so that it is the greatest multiple of
  1164.     the lineHeight that still fits in the old viewRect. */
  1165.  
  1166. #define __SEG__ Main
  1167. void AdjustViewRect(docTE)
  1168.     TEHandle    docTE;
  1169. {
  1170.     TEPtr        te;
  1171.     
  1172.     te = *docTE;
  1173.     te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1174.                             * te->lineHeight) + te->viewRect.top;
  1175. } /*AdjustViewRect*/
  1176.  
  1177.  
  1178. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1179.     values. This is really useful when the window has been resized such that the
  1180.     scrollbars became inactive but the TERec was already scrolled. */
  1181.  
  1182. #define __SEG__ Main
  1183. void AdjustTE(window)
  1184.     WindowPtr    window;
  1185. {
  1186.     TEPtr        te;
  1187.     
  1188.     te = *((DocumentPeek)window)->docTE;
  1189.     TEScroll((te->viewRect.left - te->destRect.left) -
  1190.             GetCtlValue(((DocumentPeek)window)->docHScroll),
  1191.             (te->viewRect.top - te->destRect.top) -
  1192.                 (GetCtlValue(((DocumentPeek)window)->docVScroll) *
  1193.                 te->lineHeight),
  1194.             ((DocumentPeek)window)->docTE);
  1195. } /*AdjustTE*/
  1196.  
  1197.  
  1198. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1199.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1200.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1201.     width to the width of the viewRect. The current values are set by comparing the offset between
  1202.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1203.     calling ShowControl. */
  1204.  
  1205. #define __SEG__ Main
  1206. void AdjustHV(isVert,control,docTE,canRedraw)
  1207.     Boolean        isVert;
  1208.     ControlHandle control;
  1209.     TEHandle    docTE;
  1210.     Boolean        canRedraw;
  1211. {
  1212.     short        value, lines, max;
  1213.     short        oldValue, oldMax;
  1214.     TEPtr        te;
  1215.     
  1216.     oldValue = GetCtlValue(control);
  1217.     oldMax = GetCtlMax(control);
  1218.     te = *docTE;                            /* point to TERec for convenience */
  1219.     if ( isVert ) {
  1220.         lines = te->nLines;
  1221.         /* since nLines isn’t right if the last character is a return, check for that case */
  1222.         if ( *(*te->hText + te->teLength - 1) == crCharacter )
  1223.             lines += 1;
  1224.         max = lines - ((te->viewRect.bottom - te->viewRect.top) /
  1225.                 te->lineHeight);
  1226.     } else
  1227.         max = maxDocWidth - (te->viewRect.right - te->viewRect.left);
  1228.     
  1229.     if ( max < 0 ) max = 0;
  1230.     SetCtlMax(control, max);
  1231.     
  1232.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1233.         memory. This is why we don’t just do it once at the beginning. */
  1234.     te = *docTE;
  1235.     if ( isVert )
  1236.         value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1237.     else
  1238.         value = te->viewRect.left - te->destRect.left;
  1239.     
  1240.     if ( value < 0 ) value = 0;
  1241.     else if ( value >  max ) value = max;
  1242.     
  1243.     SetCtlValue(control, value);
  1244.     /* now redraw the control if it needs to be and can be */
  1245.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1246.         ShowControl(control);
  1247. } /*AdjustHV*/
  1248.  
  1249.  
  1250. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1251.  
  1252. #define __SEG__ Main
  1253. void AdjustScrollValues(window,canRedraw)
  1254.     WindowPtr    window;
  1255.     Boolean        canRedraw;
  1256. {
  1257.     DocumentPeek doc;
  1258.     
  1259.     doc = (DocumentPeek)window;
  1260.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1261.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1262. } /*AdjustScrollValues*/
  1263.  
  1264.  
  1265. /* Re-calculate the position and size of the viewRect and the scrollbars. */
  1266.  
  1267. #define __SEG__ Main
  1268. void AdjustScrollSizes(window)
  1269.     WindowPtr    window;
  1270. {
  1271.     Rect        teRect;
  1272.     DocumentPeek doc;
  1273.     
  1274.     doc = (DocumentPeek) window;
  1275.     GetTERect(window, &teRect);
  1276.     (*doc->docTE)->viewRect = teRect;
  1277.     AdjustViewRect(doc->docTE);
  1278.     MoveControl(doc->docVScroll, window->portRect.right - scrollbarAdjust, -1);
  1279.     SizeControl(doc->docVScroll, scrollbarWidth, window->portRect.bottom - 
  1280.                 window->portRect.top - growboxAdjust);
  1281.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - scrollbarAdjust);
  1282.     SizeControl(doc->docHScroll, window->portRect.right - 
  1283.                 window->portRect.left - growboxAdjust, scrollbarWidth);
  1284. } /*AdjustScrollSizes*/
  1285.  
  1286.  
  1287. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1288.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1289.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1290.     by jamming a $FF in their contrlVis fields. */
  1291.  
  1292. #define __SEG__ Main
  1293. void AdjustScrollbars(window,needsResize)
  1294.     WindowPtr    window;
  1295.     Boolean        needsResize;
  1296. {
  1297.     DocumentPeek doc;
  1298.     
  1299.     doc = (DocumentPeek) window;
  1300.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1301.     (*doc->docVScroll)->contrlVis = controlInvisible;    /* turn them off */
  1302.     (*doc->docHScroll)->contrlVis = controlInvisible;
  1303.     if ( needsResize )                                    /* move & size as needed */
  1304.         AdjustScrollSizes(window);
  1305.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1306.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1307.     (*doc->docVScroll)->contrlVis = controlVisible;        /* turn them on */
  1308.     (*doc->docHScroll)->contrlVis = controlVisible;
  1309. } /* AdjustScrollbars */
  1310.  
  1311.  
  1312. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1313.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1314.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1315.     amount, then restores the clip region. */
  1316.  
  1317. #define __SEG__ Main
  1318. pascal void PascalClikLoop()
  1319. {
  1320.     WindowPtr    window;
  1321.     RgnHandle    region;
  1322.     
  1323.     window = FrontWindow();
  1324.     region = NewRgn();
  1325.     GetClip(region);                    /* save clip */
  1326.     ClipRect(&window->portRect);
  1327.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1328.     SetClip(region);                    /* restore clip */
  1329.     DisposeRgn(region);
  1330. } /* PascalClikLoop */
  1331.  
  1332.  
  1333. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1334.     turn called by the TEClick toolbox routine. It returns the address of the
  1335.     default clikLoop routine that was put into the TERec by TEAutoView to
  1336.     AsmClikLoop so that it can call it. */
  1337.  
  1338. #define __SEG__ Main
  1339. pascal ProcPtr GetOldClikLoop()
  1340. {
  1341.     return ((DocumentPeek)FrontWindow())->docClik;
  1342. } /* GetOldClikLoop */
  1343.  
  1344.  
  1345. /*    Check to see if a window belongs to the application. If the window pointer
  1346.     passed was NIL, then it could not be an application window. WindowKinds
  1347.     that are negative belong to the system and windowKinds less than userKind
  1348.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1349.     mean it is a dialog. */
  1350.  
  1351. #define __SEG__ Main
  1352. Boolean IsAppWindow(window)
  1353.     WindowPtr    window;
  1354. {
  1355.     short        windowKind;
  1356.     
  1357.     if ( window == nil )
  1358.         return false;
  1359.     else {    /* application windows have windowKinds >= userKind (8) or dialogKind (2) */
  1360.         windowKind = ((WindowPeek) window)->windowKind;
  1361.         return (windowKind >= userKind) || (windowKind == dialogKind);
  1362.     }
  1363. } /*IsAppWindow*/
  1364.  
  1365.  
  1366. /* Check to see if a window belongs to a desk accessory. */
  1367.  
  1368. #define __SEG__ Main
  1369. Boolean IsDAWindow(window)
  1370.     WindowPtr    window;
  1371. {
  1372.     if ( window == nil )
  1373.         return false;
  1374.     else    /* DA windows have negative windowKinds */
  1375.         return ((WindowPeek) window)->windowKind < 0;
  1376. } /*IsDAWindow*/
  1377.  
  1378.  
  1379. /*    Check to see if a given trap is implemented. This is only used by the
  1380.     Initialize routine in this program, so we put it in the Initialize segment.
  1381.     The recommended approach to see if a trap is implemented is to see if
  1382.     the address of the trap routine is the same as the address of the
  1383.     Unimplemented trap. */
  1384.  
  1385. #define __SEG__ Initialize
  1386. Boolean TrapAvailable(tNumber,tType)
  1387.     short        tNumber;
  1388.     TrapType    tType;
  1389. {
  1390.     /* Check and see if the trap exists. On 64K ROM machines, tType will be ignored. */
  1391.  
  1392.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  1393. } /*TrapAvailable*/
  1394.